#!/usr/bin/python3
#
# gen_utils.py - utils for gen_header and gen_tables
#
# Copyright (C) 2013 Matthew R. Wette
# mwette@alumni.caltech.edu
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307, USA.
#
# The GNU General Public License is contained in the file COPYING.
#
# v130224a

import sys, os, re, difflib
import pdb

def write_w_fill(f1, col, text, leader = "  ", fillcol = 76, cc=""):
    """
    Write text to f1 and increment column.  If column > fillcol, wrap
    with leader
    """
    ln = len(text)
    if col + ln > fillcol:
        f1.write(cc + "\n" + leader)
        col = len(leader)
    f1.write(text)
    col = col + ln
    return col

def replace_in_code(arg, fname, tag, rout):
    """
    Generate filename.new with lines between /* tag: beg */ and /* tag: end */
    replaced by lines generated by the function rout(arg, f)  where arg is a
    user argument, and f is the file handle for writing. 
    """
    f0 = open(fname, 'r')
    f1 = open(fname + ".new", 'w')
    tbeg = "/* %s: beg */" % (tag,)
    tend = "/* %s: end */" % (tag,)
    # Copy part upto the begin-tag.
    l0 = f0.readline()
    while l0:
        f1.write(l0)
        if l0.lstrip().startswith(tbeg):
            break
        l0 = f0.readline()
    if not l0:
        # no tag found
        f0.close()
        f1.close()
        print("*** no beg tag found")
        return
    # Insert user code.
    rout(arg, f1)
    # Skip over guts and continue with rest of source.
    l0 = f0.readline()
    while l0:
        if l0.lstrip().startswith(tend):
            f1.write(l0)
            break
        l0 = f0.readline()
    if not l0:
        # no tag found
        f0.close()
        f1.close()
        return
    l0 = f0.readline()
    while l0:
        f1.write(l0)
        l0 = f0.readline()
    f0.close()
    f1.close()

def move_if_changed(fname):
    """
    If fname.new is changed wrt fname, then rename fname to fname.old and
    fname.new to fname.
    """
    fname_old = fname + ".old"
    fname_new = fname + ".new"
    if os.system("cmp " + fname + " " + fname_new + ">/dev/null"):
        os.rename(fname, fname_old)
        os.rename(fname_new, fname)
        return True
    else:
        return False

# --- last line ---
